import React, { useMemo, useRef } from "react";
import {
  DataSet,
  Table,
  Form,
  TextField,
  DateTimePicker,
  Select,
  NumberField,
  TextArea,
} from "choerodon-ui/pro";
import { HCES_HTMS, API_HOST } from "tms-front/lib/common/config";
import { getCurrentOrganizationId } from "utils/utils";
import styled from "styled-components";
import request from "utils/request";

import MacroNotification from "tms-front/lib/common/htms/components/MacroNotification";

import CustomUpload from "tms-front/lib/components/CustomUpload";

// TH_OM_DISPATCH 订单调度

// OM202212000016

const currentTenantID = getCurrentOrganizationId();

function macroRequest(params): Promise<any> {
  return request(`${HCES_HTMS}/v1/${currentTenantID}/tp/macro/excuteMacro`, {
    body: params,
    method: "POST",
  });
}

const queryMovementDetail = `${HCES_HTMS}/v1/${currentTenantID}/htms/movement/getMovementByID`;

const defaultAction = `${API_HOST}${HCES_HTMS}/v1/${currentTenantID}/htms/file/upload`;

const ContentWrapper = styled.div`
  position: relative;
  width: ${(props) => (props.width ? props.width : "650px")};
  padding-bottom: 60px;
`;

const FormWrapper = styled.div`
  .c7n-pro-field-required & .c7n-pro-field-label {
    &::after {
      content: none !important;
    }
  }
`;

const Footer = styled.div`
  position: absolute;
  bottom: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: 100%;
  height: 50px;
  border-top: 0.01rem solid #e0e0e0;
  background-color: #fff;

  .button {
    display: flex;
    flex: none;
    align-items: center;
    justify-content: content;
    height: 28px;
    padding: 0px 12px;
    border-radius: 2px;
    cursor: pointer;
    transition: 0.3s;
  }

  .cancel {
    color: #000000d9;
    background-color: #fff;
    border: 1px solid #e6e6e6;

    &:hover {
      border-color: #29becf;
      color: #29becf;
      background-color: #fff;
    }

    &:active {
      border-color: #1995a8;
      color: #1995a8;
      background-color: #fff;
    }
  }

  .confirm {
    margin-left: 10px;
    margin-right: 15px;
    color: #fff;
    background-color: #29becf;
    border-color: #29becf;
    cursor: pointer;

    &:hover {
      color: #ffffff;
      background-color: #79e4e8;
      border-color: #79e4e8;
    }

    &:active {
      color: #fff;
      background-color: #1995a8;
      border-color: #1995a8;
    }
  }
`;

const movementLineDs = () => ({
  autoQuery: false,
  paging: false,
  fields: [
    {
      name: "itemXid",
      label: "物料编码",
    },
    {
      name: "itemName",
      label: "物料名称",
    },
    {
      name: "itemCount",
      label: "数量",
    },
    {
      name: "weight",
      label: "重量",
    },
    {
      name: "volume",
      label: "体积",
    },
  ],
});

const movementDs = () => ({
  autoQuery: false,
  fields: [
    {
      name: "xid",
      label: "订单号",
      disabled: true,
    },
    {
      name: "attribute6",
      label: "车牌号",
      disabled: true,
    },
    {
      name: "attribute5",
      label: "司机姓名",
      disabled: true,
    },
    {
      name: "attribute7",
      label: "联系电话",
      disabled: true,
    },
    {
      name: "startShippingDate",
      label: "接货时间",
      type: "dateTime",
      required: true,
    },
    {
      name: "signDate",
      label: "交货时间",
      type: "dateTime",
      required: true,
    },
    {
      name: "chargeMethod",
      label: "计费方式",
      lookupCode: "HACS.MADA_CHARGE_METHOD",
      disabled: true,
    },
    {
      name: "attribute26",
      label: "里程（KM）",
      required: true,
    },
    {
      name: "attribute25",
      label: "计费数量",
      required: true,
    },
    {
      name: "dimCount",
      label: "签收数量",
      required: true,
    },
    {
      name: "remark",
      label: "备注",
    },
  ],
  children: {
    movementLine: new DataSet(movementLineDs()),
  },
  transport: {
    read: ({ params, data }) => {
      return {
        url: queryMovementDetail,
        method: "GET",
        params: {
          ...params,
          ...data,
        },
      };
    },
  },
});

const App = (props) => {
  const { record, targetModal } = props;
  //   console.log('props', props);

  const uploadRef = useRef();

  const uploadProps = {
    data: {
      sourceType: "uploadShipmenttReturn",
      sourceKey: record.id,
    },
    params: {
      sourceType: "uploadShipmenttReturn",
      sourceKey: record.id,
    },

    type: "card",
    uploadBtnFont: "上传附件",
    style: { marginLeft: 100 },
    total: 10,
    title: "上传",
    okText: "确定",
    action: defaultAction,
    isMultiple: "preview",
  };

  const movementFormDs = useMemo(() => {
    // @ts-ignore
    const dataSet = new DataSet(movementDs());
    const { id } = record;
    dataSet.setQueryParameter("id", id);
    dataSet.query();

    return dataSet;
  }, []);

  const columns = [
    {
      name: "itemXid",
    },
    {
      name: "itemName",
    },
    {
      name: "itemCount",
    },
    {
      name: "weight",
    },
    {
      name: "volume",
    },
  ];

  const cancel = () => {
    targetModal.close();
  };

  const confirm = async () => {
    const { current } = movementFormDs;

    if (!current) return;

    // 保存更新
    if (!(await current.validate(true))) return;

    // 图片上传
    await uploadRef.current.handleUpload();

    const body = {
      paramIn: {
        list: [{ id: record.id }],
        ...current.toData(),
      },
      macroCode: "TH_OM_UPLOAD_EPOD",
    };

    const res = await macroRequest(body);

    MacroNotification.open({
      ...res,
      onSuccess: () => {
        // this.initData();
        targetModal.close();
      },
    });
  };

  return (
    <>
      <ContentWrapper>
        <FormWrapper>
          <Form dataSet={movementFormDs} columns={2} labelWidth={150}>
            <TextField name='xid' />
            <TextField name='attribute6' />
            <TextField name='attribute5' />
            <TextField name='attribute7' />
            <DateTimePicker name='startShippingDate' />
            <DateTimePicker name='signDate' />
            <Select name='chargeMethod' />
            <NumberField name='attribute26' />
            <NumberField name='attribute25' />
            <NumberField name='dimCount' />
            <TextArea name='remark' colSpan={2} />
          </Form>
        </FormWrapper>
        <Table
          dataSet={movementFormDs.children.movementLine}
          columns={columns}
        />
        <div style={{ marginBottom: 15 }} />
        <CustomUpload ref={uploadRef} {...uploadProps} />
      </ContentWrapper>
      <Footer>
        <div
          className='button cancel'
          onClick={() => {
            cancel();
          }}
        >
          取消
        </div>
        <div
          className='button confirm'
          onClick={() => {
            confirm();
          }}
        >
          确认
        </div>
      </Footer>
    </>
  );
};

export default App;
